package com.sds.smarthome.foundation.util;

import android.content.Context;
import android.os.Process;

import com.google.gson.JsonObject;
import com.jiongbull.jlog.Logger;
import com.jiongbull.jlog.constant.LogSegment;
import com.jiongbull.jlog.storage.disk.DiskConfigs;
import com.jiongbull.jlog.storage.disk.DiskStorage;
import com.sds.smarthome.foundation.DataSourceFactory;
import com.sds.smarthome.foundation.SHLogger;

import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public final class XLog {

    private static Logger sLogger;
    private static SHLogger shLogger;
    private static String sClientId = "";
    private static final int PID = Process.myPid();
    private static SimpleDateFormat sFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    private static boolean sEnableUpload;


    public static void init(Context context, boolean debug, boolean writeFile, String logDir) {
        DiskConfigs diskConfigs = DiskConfigs.Builder.newBuilder()
                .setCapacity(100 * 1024 * 1024)
                .build();
        sLogger = Logger.Builder.newBuilder(context, "XLog")
                .setDebug(debug)
                .setWriteToFile(writeFile)
                .setLogDir(logDir)
                .setLogSegment(LogSegment.ONE_HOUR)
                .setTimeFormat("yyyy-MM-dd HH:mm:ss")
                .setPackagedLevel(1)
                .setStorage(new DiskStorage(diskConfigs))
                .build();
        shLogger = DataSourceFactory.getCloudLogApi();
    }

    public static void d(String msg) {
        sLogger.d(msg);
    }

    public static void i(String msg) {
        sLogger.i(msg);
    }

    public static void f(String msg) {
        sLogger.wtf(msg);
        if(!sEnableUpload)
            return;
        JsonObject json = new JsonObject();
        json.addProperty("info","["+sFormatter.format(new Date())+" ("+PID+":"+Thread.currentThread().getId()+")]"+msg);
        shLogger.sendLog(sClientId,json).enqueue(new Callback<Void>() {
            @Override
            public void onResponse(Call<Void> call, Response<Void> response) {
            }

            @Override
            public void onFailure(Call<Void> call, Throwable t) {

            }
        });
    }

    public static void w(String msg) {
        sLogger.w(msg);
    }

    public static void e(String msg) {
        sLogger.e(msg);
    }

    public static void e(Throwable exception) {
        sLogger.e(exception);
    }

    public static void setClientId(String clientId) {
        XLog.sClientId = clientId;
    }

    public static void setEnableUpload(boolean sEnableUpload) {
        XLog.sEnableUpload = sEnableUpload;
    }
}
